﻿//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon Company Limited.
//
// Licensed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////
#include "CmdFinishDrawRoofProfile.h"
#include "GmUiStructureCommandRegister.h"
#include "StructureCmdIds.h"
#include "CmdStatusUtils.h"

#include "IEditMode.h"
#include "StructureEditModeTypes.h"
#include "IStructureRoofEditModeBehavior.h"
#include "RoofCustomData.h"
#include "IStructureSlopeLine.h"
#include "StructureRoofProfileUsedModelLineUtils.h"
#include "StructureEditProfileUtils.h"
#include "StructureInstanceCmdUtils.h"
#include "StructureRoofInput.h"
#include "IStructureRoof.h"

#include "IDocument.h"
#include "IUiDocument.h"
#include "IModelView.h"
#include "IPlane.h"
#include "IModelLine.h"
#include "IGenericElement.h"
#include "ISelection.h"
#include "IInstance.h"
#include "IUserTransaction.h"
#include "UiCommonDialog.h"
#include "UserTransactionGroupUtils.h"
#include "GbmpBuiltInCategoryUniIdentitiesNew.h"
#include "IElementStatus.h"
#include "IHighlights.h"
#include "GbmpDocUtils.h"
#include "UiDocumentViewUtils.h"

#include "EnableCompileWarning_The_LAST_IncludeInCpp.h"


using namespace gcmp;

REGISTER_GM_COMMAND(CmdFinishDrawRoofProfile)

CmdFinishDrawRoofProfile::CmdFinishDrawRoofProfile()
    : GbmpCommandBase(ID_CMD_EDIT_STRUCTURE_ROOF_FINISH)
{
}

bool CmdFinishDrawRoofProfile::IsEnabled() const
{
    CMD_ONLY_ENABLE_IN_PROJECT_ENVIRONMENT
}

bool CmdFinishDrawRoofProfile::IsVisible() const
{
    CMD_ONLY_VISIBLE_IN_PROJECT_ENVIRONMENT
}

OwnerPtr<IAction> CmdFinishDrawRoofProfile::ExecuteCommand(const CommandParameters& cmdParams)
{
    IDocument* pDoc = UiDocumentViewUtils::GetCurrentDocument();
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pDoc, L"pDoc为空",L"GDMPLab",L"2024-03-30");

    IModelView* pModelView = UiDocumentViewUtils::GetCurrentModelView();
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pModelView, L"pModelView为空",L"GDMPLab",L"2024-03-30");

    const IEditMode* pProfileEditMode = IEditMode::Get(pDoc, StructureEditModeTypes::StructureRoofProfileModeType);
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pProfileEditMode, L"pProfileEditMode为空",L"GDMPLab",L"2024-03-30");

    const IStructureRoofEditModeBehavior* pProfileEditModeBehavior = quick_cast<const IStructureRoofEditModeBehavior>(pProfileEditMode->GetEditModeBehavior());
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pProfileEditModeBehavior, L"pProfileEditModeBehavior为空",L"GDMPLab",L"2024-03-30");

    bool bIsCreating = pProfileEditMode->GetIsCreating();
    ElementId familyId = pProfileEditModeBehavior->GetEditingFamilyId();
    ElementId instanceTypeId = pProfileEditModeBehavior->GetEditingInstanceTypeId();

    // 获取当前文档里的轮廓线
    std::vector<IModelLine*> modelLines;
    StructureRoofProfileUsedModelLineUtils::GetRoofProfileModelLinesInCurrentDocument(pDoc, modelLines);

    if (modelLines.empty())
    {
        UiCommonDialog::ShowMessageBox(GBMP_TR(L"警告"), GBMP_TR(L"轮廓为空，无法完成绘制轮廓！"), (int)UiCommonDialog::ButtonType::OK);
        return nullptr;
    }

    // 检查轮廓线的合法性
    OwnerPtr<IPlane> opWorkPlane = pModelView->GetWorkPlane();
    if (!StructureEditProfileUtils::CheckForValidLoops(modelLines, opWorkPlane->GetCoordinate(), false, true))
    {
        return nullptr;
    }

    // 获取当前文档中的坡度线
    std::vector<IStructureSlopeLine*> slopeLines;
    std::vector<IElement*> allSlopLineElements = gcmp::GbmpDocUtils::GetElementsByCategory(pDoc, BuiltInCategoryUniIdentities::BICU_STRUCTURE_SLOPELINE);
    FOR_EACH(pElement, allSlopLineElements)
    {
        IGenericElement* pGenericElement = quick_cast<IGenericElement>(pElement);
        DBG_WARN_AND_CONTINUE_UNLESS(pGenericElement, L"pGenericElement为空",L"GDMPLab",L"2024-03-30");

        IStructureSlopeLine* pSlope = quick_cast<IStructureSlopeLine>(pGenericElement->GetExternalObject());
        if (pSlope && ((const IGenericElement*)pGenericElement)->GetStatus()->IsVisible())
        {
            slopeLines.push_back(pSlope);
        }
    }

    // 检查屋顶坡度线和屋顶轮廓线相对关系的合法性
    std::map<IStructureSlopeLine*, IModelLine*> slopeLineAndProfileCurveMap;
    if (!StructureEditProfileUtils::CheckSlopeLineAndProfileCurveRelationshipValidity(slopeLines, modelLines, slopeLineAndProfileCurveMap))
    {
        return nullptr;
    }

    // 整理轮廓线数据
    std::vector<IModelLine*> profileCurves;
    FOR_EACH(pModelLine, modelLines)
    {
        profileCurves.push_back(pModelLine);
    }
    for (auto it = slopeLineAndProfileCurveMap.begin(); it != slopeLineAndProfileCurveMap.end(); it++)
    {
        profileCurves.push_back(it->second);
    }

    // 退出编辑模式
    if (bIsCreating)  // 创建屋顶
    {
        OwnerPtr<StructureRoofInput> opInput = NEW_AS_OWNER_PTR(StructureRoofInput);
        bool bOk = StructureInstanceCmdUtils::GenerateStructureRoofInput(pDoc, pModelView, GetCategory(), GetCategorySecondKey(), familyId, instanceTypeId, *opInput);
        DBG_WARN_AND_RETURN_NULLPTR_UNLESS(bOk, L"StructureRoofInput生成失败",L"GDMPLab",L"2024-03-30");
        opInput->ProfileCurves = profileCurves;
        opInput->SlopeLines = slopeLines;

        OwnerPtr<IUserTransaction> opTransaction = IUserTransaction::Create(pDoc, GBMP_TR(L"退出编辑环境"));

        IEditMode* pEditMode = IEditMode::Get(pDoc, StructureEditModeTypes::StructureRoofProfileModeType);
        DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pEditMode, L"pEditMode为空",L"GDMPLab",L"2024-03-30");
        pEditMode->EndEditing(pDoc);

        IStructureRoof* pRoof = IStructureRoof::Create(opInput.get());
        if (!pRoof)
        {
            UiCommonDialog::ShowMessageBox(GBMP_TR(L"警告"), GBMP_TR(L"生成形体失败，请重新绘制屋顶轮廓！"), (int)UiCommonDialog::ButtonType::OK);
            opTransaction->Rollback();
            return nullptr;
        }

        opTransaction->Commit();
    }
    else  // 编辑屋顶
    {
        ElementId instanceId = pProfileEditMode->GetEditingElementId();
        const IInstance* pInstance = quick_cast<IInstance>(pDoc->GetElement(instanceId));
        DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pInstance, L"pInstance为空",L"GDMPLab",L"2024-03-30");

        OwnerPtr<StructureRoofEditInput> opInput = NEW_AS_OWNER_PTR(StructureRoofEditInput);
        opInput->Document = pDoc;
        opInput->InstanceId = instanceId;
        opInput->ProfileCurves = profileCurves;
        opInput->SlopeLines = slopeLines;

        OwnerPtr<IUserTransaction> opTransaction = IUserTransaction::Create(pDoc, GBMP_TR(L"退出编辑环境"));

        IEditMode* pEditMode = IEditMode::Get(pDoc, StructureEditModeTypes::StructureRoofProfileModeType);
        DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pEditMode, L"pEditMode为空",L"GDMPLab",L"2024-03-30");
        pEditMode->EndEditing(pDoc);

        IStructureRoof* pRoof = IStructureRoof::Edit(opInput.get());
        if (!pRoof)
        {
            UiCommonDialog::ShowMessageBox(GBMP_TR(L"警告"), GBMP_TR(L"生成形体失败，请重新编辑屋顶轮廓！"), (int)UiCommonDialog::ButtonType::OK);
            opTransaction->Rollback();
            return nullptr;
        }
        ISelection::Get()->Clear(pDoc);
        IHighlights::Get()->Clear();
        opTransaction->Commit();
    }

    UserTransactionGroupUtils::CommitLatestActive(pDoc);

    // 更新文档
    IUiDocument* pUiDoc = UiDocumentViewUtils::GetCurrentUiDocument();
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pUiDoc, L"pUiDoc为空",L"GDMPLab",L"2024-03-30");
    pUiDoc->UpdateView();

    return nullptr;
}

UniIdentity CmdFinishDrawRoofProfile::GetCategory() const
{
    UniIdentity categoryUid = BuiltInCategoryUniIdentities::BICU_NEW_ROOF;
    return categoryUid;
}

Int32 CmdFinishDrawRoofProfile::GetCategorySecondKey() const
{
    return 0;
}
